package bruce.rsync.diffitem;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.LinkedList;
import java.util.List;

import bruce.rsync.checksum.Checksum;
import bruce.rsync.checksum.LocalChecksumOutputStream;

public class LocalDiffItemOutputStream implements DiffItemOutputStream {
	private boolean isClosed = false;
	private List<DiffItem> list = new LinkedList<DiffItem>();

	@Override
	public void close() {
		isClosed = true;
	}

	@Override
	public void writeDiffItem(DiffItem item) {
		if (isClosed) {
			throw new IllegalStateException(
					"cann't write DiffItem to a closed DiffItemOutputStream .");
		}

		list.add(item);
	}

	public DiffItemInputStream toDiffItemInputStream() {
		return new LocalDiffItemInputStream(list);
	}

	public String toString() {
		StringBuilder sb = new StringBuilder(512);
		for (DiffItem item : list) {
			if (item.isMatch()) {
				sb.append("match server trunk index :" + item.getTrunkIndex()
						+ "\n");
			} else {
				sb.append("new trunk. data is :[" + new String(item.getData()))
						.append("]\n");
			}
		}
		return sb.toString();
	}

	  
	/**
	 * @throws IOException   
	 * @Title: toFile  
	 * @Description: TODO(这里用一句话描述这个方法的作用)  
	 * @param @param outputStream
	 * @param @param fileName    参数  
	 * @return void    返回类型  
	 * @throws  
	 */  
	public void toFile(LocalChecksumOutputStream outputStream, String fileName) throws IOException {
		List<Checksum> checksumList = outputStream.getChecksumList();
		File file = new File(fileName);
		FileOutputStream os = new FileOutputStream(file);
		   
		if (!file.exists()) {
			file.createNewFile();
		}

		for (DiffItem item : list) {
			if (item.isMatch()) {
				int index = item.getTrunkIndex();
				os.write(checksumList.get(index).getValue());
			} else {
				os.write(item.getData());
			}
		}
		
		os.flush();
		os.close();
	}
}
